﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

using RexToy.Numeric;

namespace RexToy.UI.WinForm.Pmlx
{
    static class ControlSizeHelper
    {
        public const string HEIGHT = "Height";
        public const string WIDTH = "Width";

        internal static void SetSize(Control c, string key, string value, ControlMetaData meta)
        {
            switch (key)
            {
                case HEIGHT:
                    Percentage perHeight;
                    if (Percentage.TryParse(value, out perHeight))
                    {
                        Assertion.IsTrue(Percentage.ZeroPercent < perHeight && perHeight < Percentage.HundredPercent, string.Format("Invalid percentage value [{0}].", perHeight));
                        var height = c.Parent.Height * perHeight;
                        c.Height = (int)height;

                        meta.Height = perHeight;
                    }
                    else
                    {
                        c.Height = int.Parse(value);

                        meta.Height = null;
                    }
                    break;

                case WIDTH:
                    Percentage perWidth;
                    if (Percentage.TryParse(value, out perWidth))
                    {
                        Assertion.IsTrue(Percentage.ZeroPercent < perWidth && perWidth < Percentage.HundredPercent, string.Format("Invalid percentage value [{0}].", perWidth));
                        var width = c.Parent.Width * perWidth;
                        c.Width = (int)width;

                        meta.Width = perWidth;
                    }
                    else
                    {
                        c.Width = int.Parse(value);

                        meta.Width = null;
                    }
                    break;

                default:
                    Assertion.Fail("Invalid property.");
                    break;
            }
        }

        internal static void Resize(List<ControlMetaData> list)
        {
            foreach (var meta in list)
            {
                Control c = meta.Control;
                if (meta.WidthResizable)
                {
                    c.Width = (int)(c.Parent.Width * meta.Width);
                }
                if (meta.HeightResizable)
                {
                    c.Height = (int)(c.Parent.Height * meta.Height);
                }
            }
        }
    }
}
